#include <iostream>
#include "mysql.h"
#include "comm.hpp"

bool InsertSql(std::string com)
{
    MYSQL *sql = mysql_init(nullptr);
    if (sql == nullptr)
    {
        std::cerr << "mysql init error" << std::endl;
        return 1;
    }

    if (mysql_real_connect(sql, "127.0.0.1", "tmp", " ", "http_test", 3306, nullptr, 0))
    {
        std::cerr << "mysql connect error" << std::endl;
    }
    else
    {
        std::cerr << "connect success" << std::endl;
    }
    mysql_set_character_set(sql, "utf8");

    
    std::cerr << "插入sql记录:" << com << std::endl;
    int ret = mysql_query(sql, com.c_str());
    std::cerr << "插入结果result:" << ret << std::endl;
    mysql_close(sql);
}

int main()
{
    //std::cout << "version:" << mysql_get_client_info() << std::endl;
    std::string com;
    if (GetQueryString(com))
    {
        std::cerr << "query_string:" << com << std::endl;
        // 数据处理
        // name=xxx&password=xxx
        std::string name;
        std::string password;

        CutString(com, "&", name, password);

        std::string _name;
        std::string sql_name;
        CutString(name, "=", _name, sql_name);

        std::string _password;
        std::string sql_password;
        CutString(password, "=", _password, sql_password);

        std::string sql = "insert into user(name, password) values(\'";
        sql += sql_name;
        sql += "\',\'";
        sql += sql_password;
        sql += "\');";

        if (InsertSql(sql))
        {
            std::cout << "<html>";
            std::cout << "<head><meta charset=\"utf-8\"></head>";
            std::cout << "<body><h1>注册成功</h1></body>";
            std::cout << "</html>";
        }
    }

    return 0;
}